import { DatePicker, Input, InputNumber } from '@/components/AntdProxy';
import CommonDrawer from '@/components/CommonDrawer';
import { CrudFormLayout } from '@/components/Crud';
import request from '@/utils/request';
import { useAsyncEffect } from 'ahooks';
import { Form, message } from 'antd';
import dayjs from 'dayjs';

const Save = (props) => {
  const { open, record, onCancel, onOk } = props;
  const [form] = Form.useForm();

  useAsyncEffect(() => {
    if (record) {
      const formData = {
        ...record,
        day: dayjs(record.day),
      };
      form?.setFieldsValue(formData);
    }
  }, [record]);

  const handleOk = async () => {
    const values = await form.validateFields();
    const url = record ? '/datas/pettycash/update' : '/datas/pettycash/add';
    const params = {
      ...values,
      day: values.day.format('YYYY-MM-DD'),
    };
    if (record) {
      params.pettyCashId = record?.pettyCashId;
    }
    await request({
      url,
      method: 'POST',
      data: params,
    });
    message.success('操作成功');
    onOk?.();
  };

  return (
    <CommonDrawer
      title={record ? '更新备用金信息' : '新建备用金信息'}
      open={true}
      onClose={onCancel}
      onOk={handleOk}
      afterOpenChange={(visible) => {
        if (!visible) {
          form.resetFields();
        }
      }}
      width={280}
      destroyOnHidden
    >
      <Form form={form} layout="vertical" style={{ height: '100%' }}>
        <CrudFormLayout itemMinWidth={180}>
          <Form.Item label="日期" name="day">
            <DatePicker needConfirm={false} placeholder="请选择日期" />
          </Form.Item>
          <Form.Item label="金额" name="price">
            <InputNumber min={0} />
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input.TextArea maxLength={150} rows={3} />
          </Form.Item>
        </CrudFormLayout>
      </Form>
    </CommonDrawer>
  );
};

export default Save;
